import 'package:auto_route/annotations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:sonora/bloc/followList/sj_follow_list_bloc.dart';
import 'package:sonora/bloc/followList/sj_follow_list_event.dart';
import 'package:sonora/bloc/followList/sj_follow_list_state.dart';
import 'package:sonora/bloc/medal/sj_medal_bloc.dart';
import 'package:sonora/bloc/medal/sj_medal_event.dart';
import 'package:sonora/bloc/medal/sj_medal_state.dart';
import 'package:sonora/bloc/mine/sj_mine_bloc.dart';
import 'package:sonora/bloc/mine/sj_mine_event.dart';
import 'package:sonora/bloc/mine/sj_mine_state.dart';
import 'package:sonora/config/sj_app_initial.dart';
import 'package:sonora/models/sj_medal_data.dart';
import 'package:sonora/shared/lib/constants/sj_colors.dart';
import 'package:sonora/utils/sj_text_style.dart';
import 'package:sonora/views/appbar/sj_appbar.dart';
import 'package:sonora/views/dialog/sj_medal_upgrade_dailog.dart';
import 'package:sonora/views/navigation/routes/sj_app_router.dart';

import 'dialog/sj_medal_obtain_dailog.dart';

@RoutePage()
class SjMedalStorePage extends StatefulWidget {
  const SjMedalStorePage({super.key});

  @override
  State<SjMedalStorePage> createState() => _SjMedalStorePageState();
}

class _SjMedalStorePageState extends State<SjMedalStorePage> {
  late final SjMedalBloc medalBloc = getit<SjMedalBloc>();

  _SjMedalStorePageState();
  @override
  void initState() {
    super.initState();
    medalBloc
      ..add(const SjMedalEventLoadedUserInfo())
      ..add(const SjMedalEventLoadedMedal());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true, // 使内容延伸到导航
        appBar: SjAppbar(
          title: const Text(
            'Medal Store',
            style: SjTextStyle.customFontBlack20,
          ),
          backgroundColor: Colors.transparent, // 设置导航栏背景为透明
          elevation: 0, // 去除导航栏阴影
          leading: IconButton(
            icon: Image.asset('assets/images/nav_back.png'), // 左侧按钮
            onPressed: () {
              // 处理返回逻辑
              Navigator.of(context).pop();
            },
          ),
        ),
        body: BlocProvider.value(
          value: medalBloc,
          child: BlocListener<SjMedalBloc, SjMedalState>(
            listener: (bContext, state) {
              if (state.loading) {
                EasyLoading.show(status: 'Loading...');
              } else {
                EasyLoading.dismiss();
                if (state.errorMsg != null && state.errorMsg!.isNotEmpty) {
                  EasyLoading.showError(state.errorMsg ?? '');
                }
              }
            },
            child: Container(
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/profile_bg_me.png'),
                    fit: BoxFit.cover,
                  ),
                ),
                child: SafeArea(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: Column(children: [
                      Container(
                          padding: const EdgeInsets.symmetric(vertical: 12),
                          decoration: BoxDecoration(
                            color: SjColors.whiteColor,
                            border: Border.all(
                              color: Colors.black, // Border color
                              width: 2, // Border width
                            ),
                            borderRadius:
                                const BorderRadius.all(Radius.circular(12.0)),
                          ),
                          child: BlocBuilder<SjMedalBloc, SjMedalState>(
                              builder: (bContext, state) {
                            return Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Container(
                                        padding: const EdgeInsets.fromLTRB(
                                            17, 5, 17, 2),
                                        decoration: const BoxDecoration(
                                          color: SjColors.themeAColor,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(10.0)),
                                        ),
                                        child: Row(children: const [
                                          Text(
                                            'Click on the medal style above to equip',
                                            style:
                                                SjTextStyle.customFontTheme12,
                                          )
                                        ]),
                                      )
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 8,
                                  ),
                                  _medal1Widget(bContext, state),
                                  _medal2Widget(bContext, state),
                                  _medal3Widget(bContext, state)
                                ]);
                          })),
                    ]),
                  ),
                ))),
        ));
  }

  Widget _medal1Widget(BuildContext bContext, SjMedalState state) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.asset('assets/images/xz_sm_1.png'),
        const SizedBox(
          width: 21,
        ),
        InkWell(
          child: Image.asset('assets/images/medal_upgrade_icon.png'),
          onTap: () {
            if (state.medal1IsObtain == null || state.medal1IsObtain == false) {
              EasyLoading.showToast(
                  'You must first go to get the initial medal',
                  duration: const Duration(seconds: 3));
              return;
            }
            if (state.medal1IsUpgrade != null &&
                state.medal1IsUpgrade == true) {
              EasyLoading.showToast('You have upgraded medal',
                  duration: const Duration(seconds: 3));
              return;
            }
            showDialog(
                barrierDismissible: false,
                context: bContext,
                builder: (BuildContext dContext) {
                  return SjMedalUpgradeDialog(
                    content: 'Do you want to upgrade this medal?',
                    onAgree: () {
                      WidgetsBinding.instance.addPostFrameCallback((_) {
                        if (state.userInfoData != null &&
                            state.userInfoData?.availableCoins != null &&
                            state.userInfoData!.availableCoins! >= 25) {
                          medalBloc.add(SjMedalEvent.reviewModeConsume(
                              outlay: 25,
                              callback: () {
                                showDialog(
                                    barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext dContext) {
                                      return SjMedalObtainDialog(
                                        assetPath:
                                            'assets/images/xz_bg_y_1.png',
                                        content:
                                            'Congratulations on your new medal!',
                                        onAgree: () {
                                          // Navigator.pop(context, true);
                                        },
                                        onCancel: () {},
                                      );
                                    });
                              }));
                        } else {
                          _showNotEnoughCoinDialog(
                              context, state.medalList![0], 25);
                        }
                      });
                    },
                    onCancel: () {},
                  );
                });
          },
        ),
        const SizedBox(
          width: 10,
        ),
        Column(
          children: [
            Opacity(
              opacity: 0,
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/deal_img_icon.png',
                    width: 20,
                    height: 20,
                  ),
                  const Text(
                    '25',
                    style: SjTextStyle.customFontBlack16,
                  )
                ],
              ),
            ),
            Stack(
              children: [
                Image.asset('assets/images/xz_bg_y_1.png'),
                (state.medal1IsUpgrade != null && state.medal1IsUpgrade == true)
                    ? const SizedBox()
                    : InkWell(
                        onTap: () {
                          if (state.medal1IsObtain == null ||
                              state.medal1IsObtain == false) {
                            EasyLoading.showToast(
                                'You must first go to get the initial medal',
                                duration: const Duration(seconds: 3));
                            return;
                          }
                          if (state.medal1IsUpgrade != null &&
                              state.medal1IsUpgrade == true) {
                            EasyLoading.showToast('You have upgraded medal',
                                duration: const Duration(seconds: 3));
                            return;
                          }
                          showDialog(
                              barrierDismissible: false,
                              context: bContext,
                              builder: (BuildContext dContext) {
                                return SjMedalUpgradeDialog(
                                  content: 'Do you want to upgrade this medal?',
                                  onAgree: () {
                                    WidgetsBinding.instance
                                        .addPostFrameCallback((_) {
                                      if (state.userInfoData != null &&
                                          state.userInfoData?.availableCoins !=
                                              null &&
                                          state.userInfoData!.availableCoins! >=
                                              25) {
                                        medalBloc
                                            .add(SjMedalEvent.reviewModeConsume(
                                                outlay: 25,
                                                callback: () {
                                                  showDialog(
                                                      barrierDismissible: false,
                                                      context: context,
                                                      builder: (BuildContext
                                                          dContext) {
                                                        return SjMedalObtainDialog(
                                                          assetPath:
                                                              'assets/images/xz_bg_y_1.png',
                                                          content:
                                                              'Congratulations on your new medal!',
                                                          onAgree: () {
                                                            // Navigator.pop(
                                                            //     context, true);
                                                          },
                                                          onCancel: () {},
                                                        );
                                                      });
                                                }));
                                      } else {
                                        _showNotEnoughCoinDialog(
                                            context, state.medalList![0], 25);
                                      }
                                    });
                                  },
                                  onCancel: () {},
                                );
                              });
                        },
                        child: Image.asset(
                          'assets/images/xz_lock_bg.png',
                        )),
              ],
            ),
            Opacity(
              opacity: state.medal1IsUpgrade != null && state.medal1IsUpgrade == true ? 0 : 1,
              child: Row(
              children: [
                Image.asset(
                  'assets/images/deal_img_icon.png',
                  width: 20,
                  height: 20,
                ),
                const Text(
                  '25',
                  style: SjTextStyle.customFontBlack16,
                )
              ],
            )
            )
          ],
        )
      ],
    );
  }

  Widget _medal2Widget(BuildContext bContext, SjMedalState state) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.asset('assets/images/xz_sm_2.png'),
        const SizedBox(
          width: 21,
        ),
        InkWell(
          child: Image.asset('assets/images/medal_upgrade_icon.png'),
          onTap: () {
            if (state.medal2IsObtain == null || state.medal2IsObtain == false) {
              EasyLoading.showToast(
                  'You must first go to get the initial medal',
                  duration: const Duration(seconds: 3));
              return;
            } else if (state.medal2IsUpgrade != null &&
                state.medal2IsUpgrade == true) {
              EasyLoading.showToast('You have upgraded medal',
                  duration: const Duration(seconds: 3));
              return;
            }
            showDialog(
                barrierDismissible: false,
                context: bContext,
                builder: (BuildContext dContext) {
                  return SjMedalUpgradeDialog(
                    content: 'Do you want to upgrade this medal?',
                    onAgree: () {
                      WidgetsBinding.instance.addPostFrameCallback((_) {
                        if (state.userInfoData != null &&
                            state.userInfoData?.availableCoins != null &&
                            state.userInfoData!.availableCoins! >= 30) {
                          medalBloc.add(SjMedalEvent.reviewModeConsume(
                              outlay: 30,
                              callback: () {
                                showDialog(
                                    barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext dContext) {
                                      return SjMedalObtainDialog(
                                        assetPath:
                                            'assets/images/xz_bg_y_2.png',
                                        content:
                                            'Congratulations on your new medal!',
                                        onAgree: () {
                                          // Navigator.pop(context, true);
                                        },
                                        onCancel: () {},
                                      );
                                    });
                              }));
                        } else {
                          _showNotEnoughCoinDialog(
                              context, state.medalList![1], 30);
                        }
                      });
                    },
                    onCancel: () {},
                  );
                });
          },
        ),
        const SizedBox(
          width: 10,
        ),
        Column(
          children: [
            Opacity(
              opacity: 0,
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/deal_img_icon.png',
                    width: 20,
                    height: 20,
                  ),
                  const Text(
                    '25',
                    style: SjTextStyle.customFontBlack16,
                  )
                ],
              ),
            ),
            Stack(
              children: [
                Image.asset('assets/images/xz_bg_y_2.png'),
                (state.medal2IsUpgrade != null && state.medal2IsUpgrade == true)
                    ? const SizedBox()
                    : InkWell(
                        onTap: () {
                          if (state.medal2IsObtain == null ||
                              state.medal2IsObtain == false) {
                            EasyLoading.showToast(
                                'You must first go to get the initial medal',
                                duration: const Duration(seconds: 3));
                            return;
                          } else if (state.medal2IsUpgrade != null &&
                              state.medal2IsUpgrade == true) {
                            EasyLoading.showToast('You have upgraded medal',
                                duration: const Duration(seconds: 3));
                            return;
                          }
                          showDialog(
                              barrierDismissible: false,
                              context: bContext,
                              builder: (BuildContext dContext) {
                                return SjMedalUpgradeDialog(
                                  content: 'Do you want to upgrade this medal?',
                                  onAgree: () {
                                    WidgetsBinding.instance
                                        .addPostFrameCallback((_) {
                                      if (state.userInfoData != null &&
                                          state.userInfoData?.availableCoins !=
                                              null &&
                                          state.userInfoData!.availableCoins! >=
                                              30) {
                                        medalBloc
                                            .add(SjMedalEvent.reviewModeConsume(
                                                outlay: 30,
                                                callback: () {
                                                  showDialog(
                                                      barrierDismissible: false,
                                                      context: context,
                                                      builder: (BuildContext
                                                          dContext) {
                                                        return SjMedalObtainDialog(
                                                          assetPath:
                                                              'assets/images/xz_bg_y_2.png',
                                                          content:
                                                              'Congratulations on your new medal!',
                                                          onAgree: () {
                                                            // Navigator.pop(
                                                            //     context, true);
                                                          },
                                                          onCancel: () {},
                                                        );
                                                      });
                                                }));
                                      } else {
                                        _showNotEnoughCoinDialog(
                                            context, state.medalList![1], 30);
                                      }
                                    });
                                  },
                                  onCancel: () {},
                                );
                              });
                        },
                        child: Image.asset('assets/images/xz_lock_bg.png')),
              ],
            ),
            Opacity(
              opacity: state.medal2IsUpgrade != null && state.medal2IsUpgrade == true ? 0 : 1,
              child: Row(
              children: [
                Image.asset(
                  'assets/images/deal_img_icon.png',
                  width: 20,
                  height: 20,
                ),
                const Text(
                  '30',
                  style: SjTextStyle.customFontBlack16,
                )
              ],
            )
            )
          ],
        )
      ],
    );
  }

  Widget _medal3Widget(BuildContext bContext, SjMedalState state) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.asset('assets/images/xz_sm_3.png'),
        const SizedBox(
          width: 21,
        ),
        InkWell(
          child: Image.asset('assets/images/medal_upgrade_icon.png'),
          onTap: () {
            if (state.medal3IsObtain == null || state.medal3IsObtain == false) {
              EasyLoading.showToast(
                  'You must first go to get the initial medal',
                  duration: const Duration(seconds: 3));
              return;
            } else if (state.medal3IsUpgrade != null &&
                state.medal3IsUpgrade == true) {
              EasyLoading.showToast('You have upgraded medal',
                  duration: const Duration(seconds: 3));
              return;
            }
            showDialog(
                barrierDismissible: false,
                context: bContext,
                builder: (BuildContext dContext) {
                  return SjMedalUpgradeDialog(
                    content: 'Do you want to upgrade this medal?',
                    onAgree: () {
                      WidgetsBinding.instance.addPostFrameCallback((_) {
                        if (state.userInfoData != null &&
                            state.userInfoData?.availableCoins != null &&
                            state.userInfoData!.availableCoins! >= 35) {
                          medalBloc.add(SjMedalEvent.reviewModeConsume(
                              outlay: 35,
                              callback: () {
                                showDialog(
                                    barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext dContext) {
                                      return SjMedalObtainDialog(
                                        assetPath:
                                            'assets/images/xz_bg_y_3.png',
                                        content:
                                            'Congratulations on your new medal!',
                                        onAgree: () {
                                          // Navigator.pop(context, true);
                                        },
                                        onCancel: () {},
                                      );
                                    });
                              }));
                        } else {
                          _showNotEnoughCoinDialog(
                              context, state.medalList![2], 35);
                        }
                      });
                    },
                    onCancel: () {},
                  );
                });
          },
        ),
        const SizedBox(
          width: 10,
        ),
        Column(
          children: [
            Opacity(
              opacity: 0,
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/deal_img_icon.png',
                    width: 20,
                    height: 20,
                  ),
                  const Text(
                    '25',
                    style: SjTextStyle.customFontBlack16,
                  )
                ],
              ),
            ),
            Stack(
              children: [
                Image.asset('assets/images/xz_bg_y_3.png'),
                (state.medal3IsUpgrade != null && state.medal3IsUpgrade == true)
                    ? const SizedBox()
                    : InkWell(
                        onTap: () {
                          if (state.medal3IsObtain == null ||
                              state.medal3IsObtain == false) {
                            EasyLoading.showToast(
                                'You must first go to get the initial medal',
                                duration: const Duration(seconds: 3));
                            return;
                          } else if (state.medal3IsUpgrade != null &&
                              state.medal3IsUpgrade == true) {
                            EasyLoading.showToast('You have upgraded medal',
                                duration: const Duration(seconds: 3));
                            return;
                          }
                          showDialog(
                              barrierDismissible: false,
                              context: bContext,
                              builder: (BuildContext dContext) {
                                return SjMedalUpgradeDialog(
                                  content: 'Do you want to upgrade this medal?',
                                  onAgree: () {
                                    WidgetsBinding.instance
                                        .addPostFrameCallback((_) {
                                      if (state.userInfoData != null &&
                                          state.userInfoData?.availableCoins !=
                                              null &&
                                          state.userInfoData!.availableCoins! >=
                                              35) {
                                        medalBloc
                                            .add(SjMedalEvent.reviewModeConsume(
                                                outlay: 35,
                                                callback: () {
                                                  showDialog(
                                                      barrierDismissible: false,
                                                      context: context,
                                                      builder: (BuildContext
                                                          dContext) {
                                                        return SjMedalObtainDialog(
                                                          assetPath:
                                                              'assets/images/xz_bg_y_3.png',
                                                          content:
                                                              'Congratulations on your new medal!',
                                                          onAgree: () {
                                                            // Navigator.pop(
                                                            //     context, true);
                                                          },
                                                          onCancel: () {},
                                                        );
                                                      });
                                                }));
                                      } else {
                                        _showNotEnoughCoinDialog(
                                            context, state.medalList![2], 35);
                                      }
                                    });
                                  },
                                  onCancel: () {},
                                );
                              });
                        },
                        child: Image.asset('assets/images/xz_lock_bg.png'),
                      ),
              ],
            ),
            Opacity(
              opacity: state.medal3IsUpgrade != null && state.medal3IsUpgrade == true ? 0 : 1,
              child: Row(
              children: [
                Image.asset(
                  'assets/images/deal_img_icon.png',
                  width: 20,
                  height: 20,
                ),
                const Text(
                  '35',
                  style: SjTextStyle.customFontBlack16,
                )
              ],
            )
            )
          ],
        )
      ],
    );
  }

  void _showNotEnoughCoinDialog(
      BuildContext context, SjMedalData medalData, int outlay) {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return SjMedalUpgradeDialog(
            content:
                'If you don’t have enough gold coins, do you want to recharge?',
            onAgree: () {
              // _medalBloc.add(SjMedalEvent.obtain1Medal());
              context.router.push(SjCoinShopRoute()).then((value) {
                if (value != null) {
                  medalBloc
                    ..add(const SjMedalEvent.loadedUserInfo())
                    ..add(const SjMedalEvent.loadedMedalData());
                }
              });
            },
            onCancel: () {},
          );
        });
  }
}
